<script setup>
import { reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../stores/auth';

const authStore = useAuthStore();
const router = useRouter();
const route = useRoute();

const form = reactive({
  username: import.meta.env.VITE_DEFAULT_USERNAME || '',
  pwd: import.meta.env.VITE_DEFAULT_PASSWORD || '123456',
});

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  pwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

const loading = ref(false);
const formRef = ref();

const handleSubmit = () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      loading.value = true;
      await authStore.login({ username: form.username, pwd: form.pwd });
      ElMessage.success('登录成功，欢迎回来');
      const redirect = route.query.redirect || '/';
      router.replace(redirect);
    } catch (error) {
      ElMessage.error(error?.message || '登录失败，请检查用户名或密码');
    } finally {
      loading.value = false;
    }
  });
};

const goRegister = () => {
  router.push({ name: 'register' });
};
</script>

<template>
  <div class="auth-page">
    <el-card class="auth-card" shadow="always">
      <div class="auth-card__header">
        <h2>课程学习平台登录</h2>
        <p>系统已自动填入体验账号，直接点击登录即可进入系统。</p>
      </div>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" size="large">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="form.pwd" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">立即登录</el-button>
          <el-button type="default" link @click="goRegister">没有账号？前往注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.auth-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f3f5ff, #e6f7ff);
  padding: 40px 20px;
}

.auth-card {
  width: 420px;
}

.auth-card__header {
  text-align: center;
  margin-bottom: 24px;
}

.auth-card__header h2 {
  font-size: 26px;
  margin-bottom: 8px;
}

.auth-card__header p {
  color: #666;
  font-size: 14px;
}
</style>

